package com.kstech.ks_gaz01.fragments

import androidx.activity.OnBackPressedCallback
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.logd
import com.blankii.androidlibrary.utils.CalcUtil
import com.kstech.ks_gaz01.XML_CONFIG
import com.kstech.ks_gaz01.XML_GROUP_ADDRESS_FAULT
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.databinding.FragmentSaveFileBinding
import com.kstech.ks_gaz01.manager.ExcelManager
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: blankii
 * created on: 2024/4/29 16:15
 * description: 导出文件界面 将应用内存中的数据list 转换成excel 并通过io 生成在平板本地目录中
 */
class SaveFileFragment :
    BaseBindingFragment<FragmentSaveFileBinding>(FragmentSaveFileBinding::inflate),
    SocketFragmentListener {
    val readBeanList = ArrayList<SocketManagerNew.ReadBean>()
    var dataList = ArrayList<DebugDataBean.Item>()
    val revAddressMap = HashMap<String, ArrayList<String>>()
    val revDataList = ArrayList<String>()
    var backPress = true
    private var workState = true
    private var currentSendPosition = 0
    private var isFinished = true


    override fun onCreateInit() {
        SocketManagerNew.startSendFault = false

        /**
         * 拦截返回按键
         */
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!backPress) {
                    isEnabled = true
                    "正在读取数据中，请稍等".showSnackBar()
                } else {
                    isEnabled = false
                    activity?.onBackPressed()
                }
            }
        })
    }

    override fun onInitView() {
        binding.apply {
            backPress.setOnClickListener {
                this@SaveFileFragment.backPress = true
                activity?.onBackPressed()
            }
            saveFile.setOnClickListener {
                if (excelName.text.toString().isNullOrEmpty()) {
                    msg2.text = "请在输入框输入需要保存的文件名称"
                    return@setOnClickListener
                }
                if (!workState) {
                    msg2.text = "正在生成excel文件，请稍后点击"
                    return@setOnClickListener
                }
                SocketManagerNew.subscribeSocketFragmentListener(this@SaveFileFragment)
                clearData()
                workState = true
                isFinished = true
                currentSendPosition = 0
                this@SaveFileFragment.backPress = false
                CoroutineScope(Dispatchers.Main).launch {
                    withContext(Dispatchers.IO) {
                        val parentList = DebugDataBean.xmlMap[XML_CONFIG]
                        parentList!!.forEach { parent ->
                            if (parent.isExistedChildTab) {
                                parent.childList.forEach { child ->
                                    if (child.isExistedGroupTab) {
                                        child.groupList.forEach { group ->
                                            dataList.addAll(group.itemList)
                                            readBeanList.add(
                                                SocketManagerNew.ReadBean(
                                                    (group.itemList[0].para0.toInt() - 1).toString(),
                                                    group.itemList[0].para2,
                                                    group.itemList.size
                                                )
                                            )
                                        }
                                    } else {
                                        dataList.addAll(child.itemList)
                                        readBeanList.add(
                                            SocketManagerNew.ReadBean(
                                                (child.itemList[0].para0.toInt() - 1).toString(),
                                                child.itemList[0].para2,
                                                child.itemList.size
                                            )
                                        )
                                    }
                                }
                            } else {
                                dataList.addAll(parent.itemList)
                                readBeanList.add(
                                    SocketManagerNew.ReadBean(
                                        (parent.itemList[0].para0.toInt() - 1).toString(),
                                        parent.itemList[0].para2,
                                        parent.itemList.size
                                    )
                                )
                            }
                        }
                        /**
                         * 加入到消息队列
                         * 不需要重新发送，底层已经负责重发了，只需要掌控发送下一个的时机
                         */
                        /**
                         * 加入到消息队列
                         * 不需要重新发送，底层已经负责重发了，只需要掌控发送下一个的时机
                         */
                        val arrayList = ArrayList<SocketManagerNew.ReadBean>()
                        while (workState) {
                            if (isFinished && currentSendPosition < readBeanList.size) {
                                isFinished = false
                                val currentReadBean = readBeanList[currentSendPosition]
                                requireActivity().runOnUiThread {
                                    binding.stateMsg.text =
                                        "发送数据地址:${currentReadBean.address}"
                                }
//                                Log.e("saveFile", "send_address:${currentReadBean.address}")
                                arrayList.clear()

                                SocketManagerNew.addReadyLooperList(false,
                                    arrayList.apply { add(currentReadBean) })
                                currentSendPosition++
                            }
                            delay(50)
                        }
                    }
                }
            }
        }
    }

    override fun writeSuccess(address: String, value: String) {

    }

    override fun readSuccess(address: String, result: ArrayList<String>) {
        if (address != XML_GROUP_ADDRESS_FAULT) {
            binding.stateMsg.text = "接收数据地址:${address}"
//            Log.e("saveFile", "rev_address:${address}")
            isFinished = true
            revAddressMap[address] = result
            revDataList.addAll(result)
            binding.msg2.text = "发送个数:${dataList.size},接收个数:${revDataList.size}"
            "发送个数:${dataList.size},接收个数:${revDataList.size}".logd(TAG)
            if (dataList.size == revDataList.size) {
                backPress = true
                binding.msg2.text = "读取控制器数据完成,开始生成excel文件"
                for (i in dataList.indices) {
                    "对接address:${dataList[i].para0}".logd(TAG)
                    dataList[i].revData =
                        CalcUtil.Hex2IntStr(revDataList[i], dataList[i].isNegativeNumber)
                }
                val fileName = binding.excelName.text.trim().toString()
                ExcelManager.writeExcel(
                    fileName, DebugDataBean.xmlMap[XML_CONFIG]!!
                )
                "${fileName}.xls 文件生成完毕，保存在文件管理器-hzaichi文件夹中".showSnackBar()
                activity?.onBackPressed()
            }
        }
    }

    private fun clearData() {
        readBeanList.clear()
        dataList.clear()
        revAddressMap.clear()
        revDataList.clear()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        SocketManagerNew.unSubscribeSocketFragmentListener()
        workState = false
        SocketManagerNew.startSendFault = true
    }
}